package com.xiyuan.smartutils.streams;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;

/**
 * 摘要输出流，写入流的同时，记录长度和更新摘要信息
 *
 * @version v1.0.0 @author lgz 2017-12-12 新建与整理
 */
public class DigestOutputStream extends FilterOutputStream {
    private MessageDigest digest;
    private long length;
    
    public DigestOutputStream(OutputStream stream, MessageDigest digest) {
        super(stream);
        this.digest = digest;
    }
    
    /**************************************************************************/
    // 写入流，同时更新摘要和数目
    
    /**************************************************************************/
    
    public void write(int b) throws IOException {
        out.write(b);
        digest.update((byte) b);
        length++;
    }
    
    public void write(byte[] b, int off, int len) throws IOException {
        out.write(b, off, len);
        digest.update(b, off, len);
        length += len;
    }
    
    public void write(byte[] b) throws IOException {
        out.write(b);
        digest.update(b);
        length += b.length;
    }
    
    /**************************************************************************/
    //获取最终摘要和数目
    
    /**************************************************************************/
    
    public MessageDigest getMessageDigest() {
        return digest;
    }
    
    public byte[] digest() {
        return digest.digest();
    }
    
    public long length() {
        return length;
    }
    
    public String toString() {
        return "[DigestOutputStream] " + digest.toString();
    }
}
